package com.cari.oa.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.cari.oa.domain.SysDeptEntity;
import com.cari.oa.domain.SysDictItemEntity;
import com.cari.oa.domain.SysUserEntity;
import com.cari.oa.service.SysDeptService;
import com.cari.oa.service.SysDictItemService;
import com.cari.oa.service.SysUserService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.StrUtils;
import com.cari.oa.util.Utils;

/**
 * 通讯录controller
 * @author --Heyyroup
 * @2013-3-19 下午3:12:25
 */
@Controller
@SessionAttributes({"username","provinces", "usercnname"})
public class ContactController {
	@Resource
    private SysUserService sysUserService;
	@Resource
    private SysDeptService sysDeptService;
	@Resource
	private SysDictItemService sysDictService;

	private static String PROVINCE_SPLIT_STRING = ",";			//SysUserEntity实体的省份记录分隔符
	
	@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
	
	@RequestMapping("/comprehensive/contact/list.do")
	public String list(String name, String selectprovince, String selectDepNo, 
			Integer curPage, ModelMap modelMap){
		if( curPage == null )	curPage = 1;
		
		List<SysUserEntity> userList = sysUserService.getContactPage(name, selectprovince, selectDepNo, curPage, Contants.PAGE_SIZE);
		long totalRecords = sysUserService.getContactCount(name, selectprovince, selectDepNo);
		long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
		
		Map<String, String> deptMap = new HashMap<String, String>();
		List<SysDeptEntity> deptList = sysDeptService.getAll();
		for(int i = 0; i < deptList.size(); ++i)
			deptMap.put(deptList.get(i).getDeptNo(), deptList.get(i).getDeptName());
		
		Map<String, String> provinceMap = new HashMap<String, String>();
		List<SysDictItemEntity> provinceList = sysDictService.getItemsByGroupName("province");
		for( int i = 0; i < provinceList.size(); ++i)
			provinceMap.put(provinceList.get(i).getValue(), provinceList.get(i).getName());
		
		Map<String, String> recordProvinceMap = new HashMap<String, String>();
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < userList.size(); ++i){
			SysUserEntity entity = userList.get(i);
			if(sb.length() > 0)	sb.delete(0, sb.length());
			
			/*
			 * 由于数据库中的记录一个用户可能关联了多个省份
			 * 因此在使用时需要对省份记录进行处理
			 * 将每个省份的英文名和中文名对应起来
			 */
			if(StrUtils.isNotEmpty(entity.getProvince())){
				String[] provinceEnnames = entity.getProvince().split(PROVINCE_SPLIT_STRING);
				for(String provinceValue : provinceEnnames)
					sb.append(provinceMap.get(provinceValue)).append(PROVINCE_SPLIT_STRING);
				if(sb.lastIndexOf(PROVINCE_SPLIT_STRING) == sb.length() - 1)
					sb.deleteCharAt(sb.length() - 1);
				
				recordProvinceMap.put(entity.getId(), sb.toString());
			}
		}
		
		modelMap.addAttribute("name", name);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("totalPage", totalPage);
        modelMap.addAttribute("totalRecords", totalRecords);
        modelMap.addAttribute("selectprovince", selectprovince);
        modelMap.addAttribute("selectDepNo", selectDepNo);
		modelMap.addAttribute("deptList", deptList);
		modelMap.addAttribute("provinceList", provinceList);
		modelMap.addAttribute("userList", userList);
		
        modelMap.addAttribute("provinceMap",provinceMap);
        modelMap.addAttribute("deptMap", deptMap);
        modelMap.addAttribute("recordProvinceMap", recordProvinceMap);
		
		return "comprehensive/contact/list";
	}
	
	@RequestMapping("/comprehensive/contact/update.do")
	public String update(String id, String qs, ModelMap modelMap){
		SysUserEntity user = sysUserService.getById(id);
		if(user == null)	return Utils.errorJsonResp("未找到对应的实体对象");
		
		List<String> treeList = sysDeptService.getTree(true);    
    	modelMap.addAttribute("treeList", treeList);
		modelMap.addAttribute("user", user);
		modelMap.addAttribute("qs", qs);
		
		return "comprehensive/contact/update";
	}
	
	@RequestMapping(value = "/comprehensive/contact/update.do", method = RequestMethod.POST)
	@ResponseBody
	public String update(String id,
			@ModelAttribute("username") String username, 
			@Valid SysUserEntity sysUserEntity, BindingResult result){
		
		sysUserService.update(sysUserEntity);
		SysOperLogController.addOperLog(username, "contact_manage", "修改用户联系方式, 被修改用户的id为:" + id);
		return Utils.normalJsonResp();
	}
}
